import { MainLeftTree } from '../constant';

export default function reducer(state = { nodes: [] }, action) {
    let { type, data } = action;
    switch(type) {
        case MainLeftTree.LOAD:
            return {...state, nodes: data};
        case MainLeftTree.SAVE:
            let s2 = JSON.parse(JSON.stringify(state)), i = s2.nodes.findIndex(x => x.id === data.id);
            if (i > -1) s2.nodes[i] = {...s2.nodes[i], link_name: data.link_name, host: data.host, port: data.port, token: data.token};
            else s2.nodes.push(data);
            return s2;
        case MainLeftTree.UPDATE_BY_INDEX:
            let s = JSON.parse(JSON.stringify(state));
            s.nodes[data.i].children = data.children;
            return s;
        case MainLeftTree.REMOVE:
            let s1 = JSON.parse(JSON.stringify(state));
            s1.nodes = s1.nodes.filter(x => x.id !== data);
            return s1;
        default:
    }
    return state;
}